<?php

namespace App\Admin\Controllers;

use App\Models\UserBookChapter;
use App\Models\UserChapterWord;
use App\Models\Users;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Faker\Provider\Uuid;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Maatwebsite\Excel\Facades\Excel;

class UserController extends Controller
{
    use HasResourceActions;


    public function getReport(Content $content)
    {
        $form = new Form(new MidExamScopes());
        $form->setTitle('统计报表');
        $form->setAction(admin_url('user/post_report'));
        $form->disableCreatingCheck();
        $form->disableViewCheck();
        $form->disableEditingCheck();
        $form->disableReset();

        $form->file('file', '选择文件');

        return $content->body($form);

    }

    public function postReport(\Illuminate\Http\Request $request)
    {

        try{
            $data = Excel::toArray(null, $request->file('file'), null, \Maatwebsite\Excel\Excel::XLSX);

            return json_encode($data);

        }catch(\Exception $e){
            $success = new MessageBag([
                'title' => "导入失败",
                "message" => $e->getMessage(),
            ]);

            return redirect('/admin/mid-exam-scope')->with(compact('success'));
        }
        $success = new MessageBag([
            'title' => "导入成功",
            "message" => "导入成功",
        ]);

        return redirect('/admin/mid-exam-scope')->with(compact('success'));
    }

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content->header('Index')->description('description')->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content->header('Detail')->description('description')->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content->header('Edit')->description('description')->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content->header('Create')->description('description')->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Users);

        $grid->id('Id');
        $grid->nick_name('微信昵称');
        $grid->avatar('图片')->image(50, 50);
        $grid->country_code('手机区号');
        $grid->mobile('手机');
        //        $grid->open_id('Open id');
        //        $grid->union_id('Union id');
        //        $grid->session_key('Session key');
        //        $grid->api_token('Api token');

        $grid->inviter_id('邀请人ID');
        $grid->channel('来源渠道');
        $grid->city('城市');
        $grid->province('省份');
        $grid->country('国家');
        //        $grid->sex('Sex');
        //        $grid->language('Language');
        $grid->grade('性别');
        $grid->description('简介');
        //$grid->remember_token('Remember token');
        $grid->created_at('创建时间');
        $grid->last_active_time('最后活跃时间')->display(function ($value){
            return $value > 0 ? date('Y-m-d H:i:s', $value) : '';
        })->sortable();
        //$grid->updated_at('Updated at');


        $grid->actions(function (Grid\Displayers\Actions $actions){
            $actions->disableView();
            $actions->disableDelete();
            $actions->disableEdit();

            $actions->append('<a href="/admin/user/clear-record?id=' . $actions->getKey() . '">清空学习记录</a>&nbsp;&nbsp;&nbsp;&nbsp;');

            $actions->append('<a href="/admin/user/clear-user?id=' . $actions->getKey() . '">重置用户</a>&nbsp;&nbsp;&nbsp;&nbsp;');
        });
        $grid->filter(function ($filter){
            $filter->disableIdFilter();
            $filter->like('mobile', '手机号码');
        });
        $grid->disableCreation();

        return $grid;
    }

    public function clearUser(Request $request)
    {

        try{
            /** @var Users $user */
            $user = Users::find($request->id);
            if (!empty($user)){
                if (!empty($user->mobile)){
                    $user->mobile = rand(2, 9) . $user->mobile;
                }
                $user->open_id = Uuid::uuid();
                $user->save();
            }


            $success = new MessageBag([
                'title' => "操作成功",
                "message" => '',
            ]);

        }catch(\Exception $e){
            $success = new MessageBag([
                'title' => "操作失败",
                "message" => $e->getMessage(),
            ]);
        }

        return back()->with(compact('success'));


    }

    public function clearRecord(Request $request)
    {
        $rules = [
            'id' => 'request|integer',
        ];

        try{
            UserBookChapter::where('user_id', $request->id)->delete();
            UserChapterWord::where('user_id', $request->id)->delete();

            $success = new MessageBag([
                'title' => "操作成功",
                "message" => '',
            ]);

        }catch(\Exception $e){
            $success = new MessageBag([
                'title' => "操作失败",
                "message" => $e->getMessage(),
            ]);
        }

        return back()->with(compact('success'));


    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Users::findOrFail($id));

        $show->id('Id');
        $show->nick_name('Nick name');
        $show->avatar('Avatar');
        $show->country_code('Country code');
        $show->mobile('Mobile');
        $show->open_id('Open id');
        $show->union_id('Union id');
        $show->session_key('Session key');
        $show->api_token('Api token');
        $show->last_active_time('Last active time');
        $show->inviter_id('Inviter id');
        $show->channel('Channel');
        $show->city('City');
        $show->province('Province');
        $show->country('Country');
        $show->sex('Sex');
        $show->language('Language');
        $show->grade('Grade');
        $show->description('Description');
        $show->remember_token('Remember token');
        $show->created_at('Created at');
        $show->updated_at('Updated at');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Users);

        $form->text('nick_name', 'Nick name');
        $form->image('avatar', 'Avatar');
        $form->text('country_code', 'Country code');
        $form->mobile('mobile', 'Mobile');
        $form->text('open_id', 'Open id');
        $form->text('union_id', 'Union id');
        $form->text('session_key', 'Session key');
        $form->text('api_token', 'Api token');
        $form->number('last_active_time', 'Last active time');
        $form->number('inviter_id', 'Inviter id');
        $form->text('channel', 'Channel');
        $form->text('city', 'City');
        $form->text('province', 'Province');
        $form->text('country', 'Country');
        $form->text('sex', 'Sex');
        $form->text('language', 'Language');
        $form->text('grade', 'Grade');
        $form->text('description', 'Description');
        $form->text('remember_token', 'Remember token');

        return $form;
    }
}
